package zhuyun.code.swipe

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import kotlin.math.abs

/**
 * @author: Administrator
 * @date: 2022/1/6
 */
class RecyclerAdapter(private val context:Context): RecyclerView.Adapter<RecyclerAdapter.SwipeViewHolder>() {
    
    class SwipeViewHolder(private val mItemView: View):RecyclerView.ViewHolder(mItemView){
        val tvContent: TextView = itemView.findViewById<TextView>(R.id.tvContent)
        val llContent: LinearLayout = itemView.findViewById<LinearLayout>(R.id.llContent)
    }

    private val mData = Array<Boolean>(20){_->false}
    private var lastOpenSwipe:SwipeLayout? = null
    private var lastPosition = -1
    private var viewHolderCount = 0

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SwipeViewHolder {
        val itemView = LayoutInflater.from(context).inflate(R.layout.item_swipe_view,null)
        viewHolderCount ++
        return SwipeViewHolder(itemView)
    }

    override fun getItemCount(): Int {
        return 20
    }

    override fun onBindViewHolder(holder: SwipeViewHolder, position: Int) {
        val layoutParams = holder.llContent.layoutParams
        layoutParams.width = ScreenUtils.getScreenWidth(context)
        holder.tvContent.text = "第${position+1}条数据"
        if(holder.itemView is SwipeLayout){
            holder.itemView.setSwipeListener(object :SwipeLayout.SwipeListener{
                override fun onOpen(isFromActionUp:Boolean,smoothScroll:Boolean) {
                    mData[position] = true
                    if(isFromActionUp){
                        if(lastPosition == -1||abs(position-lastPosition) < viewHolderCount){
                            lastOpenSwipe?.swipeClose(false, smoothScroll = true)
                        } else {
                            mData[lastPosition] = false
                        }
                        lastOpenSwipe = holder.itemView
                        lastPosition = position
                    }
                }

                override fun onClose(isFromActionUp:Boolean,smoothScroll:Boolean) {
                    mData[position] = false
                    if(isFromActionUp){
                        if(lastOpenSwipe == holder.itemView){
                            lastOpenSwipe = null
                            lastPosition = -1
                        }
                    }
                }

            })
            if(mData[position]){
                holder.itemView.swipeOpen(false, smoothScroll = false)
            } else {
                holder.itemView.swipeClose(false, smoothScroll = false)
            }
        }
    }

}